from . import index_blue
from info import redis_store
import logging
from flask import current_app, render_template, session, jsonify, request
from info.models import User, News, Category
from info.utils.response_code import RET


# 首页新闻列表
# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid,page,per_page
# 返回值: data数据
@index_blue.route("/newslist")
def newslist():
    # 獲取參數
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "5")
    # 參數類型轉換，方便分頁查詢
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception:
        page = 1
        per_page = 5

    # 分頁查詢數據，組織數據
    # 判斷是否cid==1,如果是１就表示最新新聞,按新聞時間排序
    try:
        condition = ""
        if cid != "1":
            condition = (News.category_id == cid)

        paginate = News.query.filter(condition).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="查詢新聞失敗")
    totalPage = paginate.pages  # 共有多少頁
    items = paginate.items  # 當前頁數的所有對象
    currentPage = paginate.page  # 當前頁
    newList = []
    for news in items:
        newList.append(news.to_dict())
    # 返回響應，攜帶數據
    return jsonify(errno=RET.OK, errmsg="獲取成功", totalPage=totalPage, currentPage=currentPage, newsList=newList)


# 主頁顯示
@index_blue.route('/', methods=["GET", "POST"])
def index():
    # 獲取用戶編號
    user_id = session.get("user_id")
    # 根據用戶編號獲取用戶對象
    user = None
    if user_id:
        user = User.query.get(user_id)

    # 按照點擊量查找前１０條新聞
    try:
        news_list = News.query.order_by(News.clicks).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
    # 將新聞對象轉換成列表
    click_news_list = []
    for news in news_list:
        click_news_list.append(news.to_dict())
    # 查詢所有分類，磚換字典
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    # 遍歷對象轉換成字典列表
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    # 攜帶數據，渲染頁面
    dict_data = {
        "user_info": user.to_dict() if user else "",
        "click_news_list": click_news_list,
        "categories": category_list
    }

    return render_template("news/index.html", dict_data=dict_data)


# 處理網站log
@index_blue.route("/favicon.ico")
def get_logo():
    response = current_app.send_static_file("news/favicon.ico")
    return response